package com.example.mywechatprogram.service;

import com.example.mywechatprogram.entity.Book;
import com.example.mywechatprogram.entity.Response;
import com.example.mywechatprogram.entity.UsersBook;
import com.example.mywechatprogram.mapper.BookMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
public class BookService {
    @Autowired
    BookMapper bookMapper;
    public Response addbook(String userId,String bookId){
        try {
            int index=bookMapper.addBook(userId,bookId);
            if(index==1)return new Response(Response.SERVICE_RUN_SUCCESSFULLY,bookId,"单词书添加成功");
            else return new Response(Response.SERVICE_RUN_FIELD,null,"内部错误");
        }catch (DuplicateKeyException e){
            return new Response(Response.SERVICE_RUN_FIELD,bookId,"单词书已存在");
        }catch (Exception e){
            return new Response(Response.SERVICE_RUN_FIELD,null,"内部错误");
        }
    }
    public Response delbook(String userId,String bookId){
        try {
            int index=bookMapper.delBook(userId,bookId);
            if(index>0)return new Response(Response.SERVICE_RUN_SUCCESSFULLY,bookId,"单词书删除成功");
            else if(index==0)return new Response(Response.SERVICE_RUN_FIELD,null,"单词书不存在");
            else return new Response(Response.SERVICE_RUN_FIELD,null,"内部错误");
        }catch (Exception e){
            return new Response(Response.SERVICE_RUN_FIELD,null,"内部错误");
        }
    }
    public Response query() {
        try {
            List<Book> list = bookMapper.find();
            if (!list.isEmpty()) return new Response(Response.SERVICE_RUN_SUCCESSFULLY, list, "查询成功");
            else return new Response(Response.SERVICE_RUN_FIELD, null, "内部错误");
        } catch (Exception e) {
            return new Response(Response.SERVICE_RUN_FIELD, null, "内部错误");
        }
    }

    public Response queryByUser(String UUID){
        try {
            List<UsersBook> list = bookMapper.query(UUID);
            return new Response(Response.SERVICE_RUN_SUCCESSFULLY,list,"用户单词书列表请求成功");
        }catch (Exception e){
            return new Response(Response.SERVICE_RUN_FIELD,null,"内部错误");
        }
    }
}
